const http = require('http');
const url = require('url');
const fs = require('fs');
const  { createProxyMiddleware } = require('http-proxy-middleware')

// 读取html
const html = fs.readFileSync('./index.html')

const proxyConfig = require('./proxy.config.js')

http.createServer((req, res) => {
    // 代理
    const { pathname } = url.parse(req.url, true)
    const proxyApiList = Object.keys(proxyConfig.serve.proxy)  // 获取代理的接口的列表，在配置文件中是 key键
    if(proxyApiList.includes(pathname)){  // 如果请求的接口在代理的接口列表中，就做代理
        const proxy = createProxyMiddleware(proxyConfig.serve.proxy[pathname])
        proxy(req, res)
        return
    }

    res.writeHead(200, {
        'Content-Type': 'text/html'  // 输出html
    })

    res.end(html)
}).listen(80);